<template>
  <div class="product">
    <div class="product-header">
      <div class="product-header-search">
        <div class="product-header-search-item">
          <div class="product-header-search-item-label">编号</div>
          <el-input
              v-model="searchForm.code"
              class="product-header-search-item-input"
              placeholder="请输入商品编号"
              clearable
              @keyup.enter="handleSearch"
          ></el-input>
        </div>
        <div class="product-header-search-item">
          <div class="product-header-search-item-label">商品名</div>
          <el-input
              v-model="searchForm.name"
              class="product-header-search-item-input"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter="handleSearch"
          ></el-input>
        </div>
        <div class="product-header-search-item">
          <div class="product-header-search-item-label">品牌</div>
          <el-input
              v-model="searchForm.brand"
              class="product-header-search-item-input"
              placeholder="请输入品牌"
              clearable
              @keyup.enter="handleSearch"
          ></el-input>
        </div>
        <div class="product-header-search-item">
          <div class="product-header-search-item-label">型号/规格</div>
          <el-input
              v-model="searchForm.model"
              class="product-header-search-item-input"
              placeholder="请输入型号/规格"
              clearable
              @keyup.enter="handleSearch"
          ></el-input>
        </div>
      </div>
      <div class="product-header-btn">
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="Plus" @click="handleAddProduct">新增</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="product-table">
      <el-table
          :data="tableData.list"
          v-loading="loading"
          class="product-table-main"
          border
          stripe
      >
        <el-table-column type="index" :index="computeIndex" label="序号" width="80" align="center"/>
        <el-table-column prop="code" label="编号" width="120" align="center"/>
        <el-table-column prop="name" label="商品名称" min-width="150" align="center"/>
        <el-table-column prop="brand" label="品牌" width="120" align="center">
          <template #default="{ row }">
            {{ row.brand || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="model" label="型号/规格" width="120" align="center">
          <template #default="{ row }">
            {{ row.model || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120" align="center">
          <template #default="{ row }">
            {{ row.categoryName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="最后操作用户" width="120" align="center"/>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="handleDetail(row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="product-pagination">
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="tableData.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="product-pagination-main"
      />
    </div>

    <!-- 新增商品对话框组件 -->
    <AddProductDialog
        v-model:visible="addDialogVisible"
        @success="handleAddSuccess"
    />

    <!-- 修改商品对话框组件 -->
    <EditProductDialog
        v-model:visible="editDialogVisible"
        :product-id="currentEditProductId"
        @success="handleEditSuccess"
    />

    <!-- 详情对话框组件 -->
    <ProductDetailDialog
        v-model:visible="detailDialogVisible"
        :product-id="currentDetailProductId"
        @close="detailDialogVisible = false"
    />
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import AddProductDialog from './AddProductDialog.vue'
import EditProductDialog from './EditProductDialog.vue'
import ProductDetailDialog from './ProductDetailDialog.vue'
import {listProducts, deleteProduct} from "../../../api/productApi.js";

// 对话框显示状态
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const detailDialogVisible = ref(false)
// 表格数据
const tableData = ref({
  list: [],
  total: 0
})
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10
})
// 搜索表单
const searchForm = ref({
  code: '',
  name: '',
  brand: '',
  model: ''
})
// 当前编辑的商品ID
const currentEditProductId = ref(null)
// 当前查看详情的商品ID
const currentDetailProductId = ref(null)

// 加载数据
const loadData = async (params = {}) => {
  loading.value = true
  try {
    const requestParams = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      condition: searchForm.value,
      ...params
    }
    tableData.value = await listProducts(requestParams)
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNum = 1
  loadData()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.pageNum = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.pageNum = val
  loadData()
}

// 打开新增对话框
const handleAddProduct = () => {
  addDialogVisible.value = true
}

// 新增成功回调
const handleAddSuccess = () => {
  ElMessage.success('商品新增成功')
  loadData() // 刷新表格数据
}

// 打开编辑对话框
const handleEdit = (row) => {
  currentEditProductId.value = row.id // 只传递商品ID
  editDialogVisible.value = true
}

// 编辑成功回调
const handleEditSuccess = () => {
  ElMessage.success('商品修改成功')
  loadData() // 刷新表格数据
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确认删除商品"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    await deleteProduct(row.id).then(() => {
      ElMessage.success('删除成功')
      loadData() // 刷新表格数据
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 打开详情对话框
const handleDetail = (row) => {
  currentDetailProductId.value = row.id // 只传递商品ID
  detailDialogVisible.value = true
}

// 计算序号
const computeIndex = (i) => (pagination.value.pageNum - 1) * pagination.value.pageSize + i + 1

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.product {
  display: flex;
  flex-direction: column;
  height: 100%;

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20px 0;
    border-bottom: 1px solid #eee;

    &-search {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      align-items: center;
      justify-content: flex-start;
      gap: 16px;

      &-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        &-label {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          white-space: nowrap;
          width: 80px;
        }

        &-input {
          width: 200px;
        }
      }
    }

    &-btn {
      display: flex;
      align-items: center;
      flex: 0 0 200px;
      width: 200px;
      justify-content: flex-end;
      gap: 8px;
    }
  }

  &-table {
    flex: 1;
    padding: 16px 0;

    &-main {
      width: 100%;
    }
  }

  &-pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    border-top: 1px solid #eee;

    &-main {
      .el-pagination {
        justify-content: center;
      }
    }
  }
}
</style>
